<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加商品警示条 -->
    <el-alert title="添加商品信息" type="info" show-icon center :closable="false"> </el-alert>
    <!-- 步骤条 -->
    <el-steps :active="activeIndex - 0" finish-status="success" align-center :space="200">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- tab菜单 -->
    <el-form ref="addFormRef" :model="addForm" label-width="100px" label-position="top" :rules="addFormRules">
      <el-tabs v-model="activeIndex" tab-position="left" style="height: 700px" :before-leave="beforeLeaveEvent" @tab-click="tabClicked">
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model.number="addForm.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model.number="addForm.goods_weight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_weight">
            <el-input v-model.number="addForm.goods_number" type="number"></el-input>
          </el-form-item>
          <div>
            <p>商品分类</p>
            <el-cascader :options="categoriesList" v-model="addForm.goods_cat" :props="cascaderProps" @change="handleChange"> </el-cascader>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox :label="value" v-for="(value, i) in item.attr_vals" :key="i" border></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <!-- action指定图片要上传的后台Api地址 -->
          <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headersObj" :on-success="handleSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="addForm.goods_introduce"></quill-editor>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt=""  class="preview-img">
    </el-dialog>
  </div>
</template>
<script>

export default {
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: null,
        goods_weight: null,
        goods_number: null,
        // 级联选择器选中数组
        goods_cat: [],
        //图片数组
      pics:[],
      //商品内容
      goods_introduce:''
      },
      // 表单校验
      addFormRules: {
        goods_name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        goods_price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        goods_weight: [{ required: true, message: "请输入商品重量", trigger: "blur" }],
        goods_number: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
      },
      categoriesList: [],

      //级联选择器配置
      cascaderProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
      },
      // 动态参数数据
      manyData: [],
      // 静态参数数据
      onlyData: [],
      //上传图片地址
      uploadURL: "http://www.tangxiaoyang.vip:8888/api/v2/upload",
      //文件上传时的请求头
      headersObj: {
        Authorization: JSON.parse(sessionStorage.getItem("userInfo")).token,
      },
      previewVisible:false,
      previewPath:'',

      

    };
  },
  created() {
    this.getCateGoriesList();
  },
  computed: {
    //当前选中的三级分类的id
    cateId() {
      return this.addForm.goods_cat.length === 3 ? this.addForm.goods_cat[2] : null;
    },
  },
  methods: {
    // 级联选择器
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    //标签页跳转前触发
    beforeLeaveEvent(activeName, oldActiveName) {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    //获取分类
    async getCateGoriesList() {
      const { data: res } = await this.$http.get("categories");
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类列表失败");
      }
      this.categoriesList = res.data;
      this.$message.success("获取分类列表成功");
    },
    // tabs被选中时触发
    async tabClicked() {
      // 判断是动态参数还是静态属性
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: "many" },
        });
        if (res.meta.status !== 200) {
          return this.$message.error("获取参数列表失败");
        }
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        });
        // console.log(res.data)
        this.manyData = res.data;

        // this.$message.success('获取参数列表成功')
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: "only" },
        });
        if (res.meta.status !== 200) {
          return this.$message.error("获取参数列表失败");
        }
        // console.log(res.data)
        this.onlyData = res.data;
        // this.$message.success('获取参数列表成功')
      }
    },

    //图片预览
    handlePreview(file) {
      console.log(file);
      this.previewPath=file.url
      this.previewVisible=true
    },
    // 移除图片触发
    handleRemove(file) {
      console.log(file)
      //1.先获取将要删除的图片的临时路径
      const filePath=file.response.data.tmp_path
      //2.从pic数组中，找到这个图片对应的索引值
      const i=this.addForm.pics.findIndex(item=>{
        item.pic===filePath
      })
      //3.从pics数组中移除
      this.addForm.pics.splice(i,1)
      console.log(this.addForm.pics)
    },
    //图片上传成功
    handleSuccess(response){
      console.log(response)
      this.addForm.pics.push({
        pic:response.data.tmp_path
      })
      console.log(this.addForm)
      console.log(this.addForm.pics)
    }
  },
};
</script>
<style lang="less" scoped>
.el-checkbox {
  margin-right: 10px;
}
.preview-img{
  width: 100%;
}
.ql-editor{
  min-height: 300px;
}
</style>
